﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Login.Controllers
{
    public class Cookie2Controller : Controller
    {

        public ActionResult Home()
        {
            return View();
        }

        //登录页面
        public IActionResult Index(string return_url)
        {
            ViewBag.Return_Url = return_url;
            return View();
        }

        //接收表单提交的数据
        public ActionResult Login(LoginViewModel model)
        {
            SetCookies("UserName", model.UserName);
            SetCookies("PassWord", model.PassWord);
            if (!string.IsNullOrEmpty(model.return_url))
            {
                return Redirect(model.return_url);
            }
            else
            {
                return RedirectToAction("Home");
            }
        }

        public ActionResult Page(int page)
        {


            var content = HttpContext;
            var req = Request;
            var url11 = Url;

            var list1 = content.Request.Headers.ToList();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (var item in list1)
            {
                dic.Add(item.Key, item.Value);
            }

            string UserName = GetCookies("UserName");
            string PassWord = GetCookies("PassWord");
            if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PassWord))
            {
                var url = "https://" + HttpContext.Request.Host.Value + HttpContext.Request.Path.Value;
                return RedirectToAction("Index", "Cookie2", new { return_url = url });
            }
            ViewBag.UserName = UserName;
            ViewBag.PassWord = PassWord;
            ViewBag.Page = page;
            return View();
        }



        void SetCookies(string key, string value, int minutes = 30)
        {
            if (string.IsNullOrEmpty(value))
            {
                value = "";
            }
            HttpContext.Response.Cookies.Append(key, value, new CookieOptions
            {
                Expires = DateTime.Now.AddMinutes(minutes),
                IsEssential = true
            });
        }

        string GetCookies(string key)
        {
            return HttpContext.Request.Cookies[key];
        }



        ////重定向到这个页面
        //public ActionResult Hello()
        //{
        //    string UserName = GetCookies("UserName");
        //    string PassWord = GetCookies("PassWord");

        //    if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PassWord))
        //    {
        //        return BadRequest("request is incorrect");
        //    }

        //    ViewBag.UserName = UserName;
        //    ViewBag.PassWord = PassWord;
        //    return View();
        //}



    }
}




